// pages/publish/goods/index.js
import common from '../../../common/compents.js';
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
const App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pagePower: true,
    animationData: {},
    pageSize: 20,
    showList: [],
    totalSize: 0,
    active: 0,
    period: common.weekDate().weekth,
    date_type: 2,
    sort: "rank_supplier",
    page: 1,
    shareShow: false,
    visible: true,
    src: "",
    time: '第' + common.weekDate().weekth.slice(-2) + '周 ' + common.weekDate().start + '~' + common.weekDate().end,
  },
  // 获取数据
  getData(_type) {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/myview/top/goodsrank',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        period: that.data.period,
        date_type: that.data.date_type,
        sort: that.data.sort,
        page: that.data.page,
        page_size: that.data.pageSize,
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          let _arr = [...that.data.showList, ...resapi.data.data.list];
          that.setData({
            pagePower: true,
            totalSize: (resapi.data.data.total) / that.data.pageSize,
            showList: _type == 'add' ? _arr : resapi.data.data.list,
          })
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            pagePower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 跳转商品详情
  onClick(e) {
    common.toDetail(e.currentTarget.dataset.id)
  },
  // 选择时间
  change(e) {
    // console.log('time',e.detail);
    this.setData({
      period: e.detail.period,
      date_type: e.detail.date_type,
      page: 1,
      time: e.detail.time,
    })
    wx.showLoading({
      mask: true
    })
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    this.getData();
  },
  // 标签切换
  tabChange(e) {
    // console.log(e);
    let _index = e.detail.index,
      _sort;
    if (_index == 0) {
      _sort = "rank_supplier";
    } else if (_index == 1) {
      _sort = "rank_incr_supplier";
    } else if (_index == 2) {
      _sort = "rank_new_supplier";
    }
    this.setData({
      sort: _sort,
      page: 1
    })
    wx.showLoading({
      mask: true
    })
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    this.getData();
  },
  mapChange(e) {
    // console.log(456, e)
    this.setData({
      visible: e.detail.visible
    })
  },
  renderCanvas() {
    this.setData({
      shareShow: false,
    })
    // Toast('该页面暂未开放画报功能！')
    wx.showLoading({
      mask: false,
      title: "数据画报生成中"
    })
    this.canvasHtml();
  },
  canvasHtml() {
    this.widget = this.selectComponent('.widget');
    let wxml = '',
      that = this,
      _title = JSON.parse(wx.getStorageSync('currentOrganize')),
      _info = JSON.parse(wx.getStorageSync('initInfo'));
    wxml += `<view class="canvas-content">
              <view class="liubai"></view>`;
    wxml += `<view class="head">`;
    if (this.data.sort == 'rank_supplier') {
      wxml += `<text class="sjjb">品种排行</text>`;
    } else if (this.data.sort == 'rank_incr_supplier') {
      wxml += `<text class="sjjb">涨幅排行</text>`;
    } else if (this.data.sort == 'rank_new_supplier') {
      wxml += `<text class="sjjb">新品排行</text>`;
    }
    if (_title.organization_name.length < 20) {
      wxml += `<text class="orgtitle">` + _title.organization_name + `</text>`;
    } else {
      wxml += `<text class="orgtitle">` + _title.organization_name.slice(0, 17) + '...' + `</text>`
    }
    wxml += `</view>`;
    wxml += `<view class="account">
              <text class="you">由</text>
              <text class="mingzi">` + _info.account + `分享</text>
            </view>`;
    wxml += `<view class="choosetime">
                <image class="img" src="https://bodao.mhuoba.com/static/wximages/rili.png"></image>
                <text class="time">` + this.data.time + `</text>
              </view>`
    wxml += `<view class="thead">
              <text class="grow">图书信息</text>
              <text class="tushu">销售指数</text>
              <text class="hangye">行业排名</text>
            </view>`;
    if (this.data.pagePower) {
      if (this.data.showList.length > 0) {
        let goodsArr = this.data.showList.slice(0, 20);
        for (let i = 0; i < goodsArr.length; i++) {
          wxml += `<view class="thead tbody">
                    <text class="paiming">` + goodsArr[i].sale_rank + `</text>`;
          if (goodsArr[i].cover_pic) {
            let _src = goodsArr[i].cover_pic;
            if (_src.indexOf('https:') > -1) {
              _src = goodsArr[i].cover_pic;
            } else {
              _src = goodsArr[i].cover_pic.replace(/http/, 'https');
            }
            wxml += `<image class="cover" src="` + _src + `"></image>`
          } else {
            wxml += `<view class="no-image"></view>`
          }
          if (goodsArr[i].goods_name.length > 15) {
            wxml += `<text class="goodsname">` + goodsArr[i].goods_name.slice(0, 15) + '...' + `</text>`
          } else {
            wxml += `<text class="goodsname">` + goodsArr[i].goods_name + `</text>`
          }
          wxml += `<text class="tushu">` + goodsArr[i].sale_total + `</text><text class="hangye">` + goodsArr[i].in_all_rank + `</text></view>`
        }
      } else {
        wxml += `<text class="nodata">暂无数据</text>`
      }
    } else {
      wxml += `<text class="nodata">暂无权限</text>`
    }
    wxml += `<view class="zhichi">
              <image class="ercode" src="https://bodao.mhuoba.com/static/wximages/ercode.png"></image>
              <text class="jishu">博道出版数据实验室提供技术支持</text>
            </view>`;
    wxml += `</view>`;
    let style = {
      canvasContent: {
        backgroundColor: '#FFF',
        width: 375,
        height: 1230,
        padding: 10,
      },
      liubai: {
        width: 355,
        height: 30
      },
      head: {
        width: 355,
        height: 23,
        flexDirection: 'row',
        alignItems: 'center'
      },
      sjjb: {
        width: 68,
        height: 23,
        fontSize: 16,
        color: '#07193F',
      },
      orgtitle: {
        width: 280,
        height: 18,
        fontSize: 12,
        color: '#07193F',
        marginLeft: 5
      },
      account: {
        width: 355,
        height: 18,
        fontSize: 12,
        color: '#7789AF',
        flexDirection: 'row',
        marginTop: 10
      },
      you: {
        width: 12,
        height: 18,
      },
      mingzi: {
        width: 335,
        height: 18,
      },
      choosetime: {
        width: 355,
        height: 18,
        marginTop: 15,
        flexDirection: 'row',
        alignItems: 'center',
      },
      img: {
        width: 16,
        height: 16,
      },
      time: {
        width: 335,
        height: 18,
        fontSize: 12,
        color: '#07193F',
        marginLeft: 5,
        marginTop: 2
      },
      thead: {
        width: 355,
        height: 18,
        fontSize: 12,
        flexDirection: 'row',
        marginTop: 10,
        alignItems:'center'
      },
      tushu: {
        width: 60,
        height: 18,
        fontSize: 12,
        color: '#7789AF',
        textAlign: 'right'
      },
      grow: {
        width: 245,
        height: 18,
        fontSize: 12,
        color: '#7789AF'
      },
      hangye: {
        width: 55,
        height: 18,
        fontSize: 12,
        color: '#7789AF',
        textAlign: 'right',
      },
      tbody:{
        height:39,
      },
      paiming: {
        width: 32,
        height: 18,
        fontSize: 12,
        color: '#07193F'
      },
      cover: {
        width: 36,
        height: 36,
      },
      noImage: {
        width: 36,
        height: 36,
        backgroundColor: '#D1DDF6'
      },
      goodsname: {
        width: 162,
        height: 20,
        fontSize: 12,
        color: '#07193F',
        flexWrap: 'wrap',
        marginLeft:5
      },
      nodata: {
        width: 355,
        height: 850,
        lineHeight: 850,
        color: '#7789AF',
        fontSize: 12,
        textAlign: 'center',
      },
      zhichi: {
        width: 355,
        height: 78,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: "center",
        marginTop: 20
      },
      ercode: {
        width: 48,
        height: 48,
      },
      jishu: {
        width: 180,
        height: 18,
        color: '#07193F',
        fontSize: 12,
        marginLeft: 15
      },
    }
    console.log(22, {
      wxml,
      style
    });
    const p1 = this.widget.renderToCanvas({
      wxml,
      style
    });
    p1.then((res) => {
      // console.log('canvasContent', res)
      this.canvasContent = res
      wx.hideLoading();
      Dialog.confirm({
          title: '',
          message: '画报生成成功，是否保存至手机相册',
        })
        .then(() => {
          // on confirm
          that.extraImage();
        })
        .catch(() => {
          // on cancel
        });
    })
  },
  extraImage() {
    let that = this;
    const p2 = this.widget.canvasToTempFilePath()
    p2.then(res => {
      console.log('最后1', res.tempFilePath)
      that.setData({
        src: res.tempFilePath,
        // width: this.canvasContent.layoutBox.width,
        // height: this.canvasContent.layoutBox.height
      })
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          console.log('保存图片成功', res)
          Toast('成功保存至手机相册！')
        },
        fail(res) {
          console.log('保存图片失败', res)
          Toast('保存至手机相册失败！')
        },
        complete(res) {
          console.log('保存图片动作结束', res)
          wx.hideLoading();
        }
      })
    })
  },
  touchMove() {
    // console.log(1);
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('80rpx').step();
    this.setData({
      animationData: animation.export()
    });
  },
  touchCancel() {
    // console.log(2);
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('0').step();
    this.setData({
      animationData: animation.export()
    });
  },
  touchEnd() {
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('0').step();
    this.setData({
      animationData: animation.export()
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync("token")) {
      let _title = JSON.parse(wx.getStorageSync('currentOrganize'));
      wx.setNavigationBarTitle({
        title: _title.organization_name,
      })
      this.setData({
        page: 1,
      })
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
      wx.showLoading({
        mask: true
      })
      this.getData();
    } else {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.hideLoading();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  onPageScroll: function (e) {
    let that = this;
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('80rpx').step();
    this.setData({
      animationData: animation.export()
    });
    setTimeout(() => {
      var animation = wx.createAnimation({
        duration: 500
      })
      animation.translateX('0').step();
      this.setData({
        animationData: animation.export()
      });
    }, 2000)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // console.log(111)
    if (this.data.totalSize > this.data.page) {
      this.data.page++;
      this.getData('add');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "博道出版数据实验室"
    }
  }
})